#!/bin/bash
# ==========================================
# 🚀 Flutter iOS 自动打包脚本 (双击运行)
# ==========================================

set -euo pipefail

# ✅ 确保脚本在项目根目录执行
cd "$(dirname "$0")"

# 项目配置
APP_NAME="Runner"
CONFIGURATION="Release"
EXPORT_METHOD="app-store"   # TestFlight 需要 app-store
OUTPUT_DIR="build/ios/ipa"
PROJECT_PATH="$(pwd)/ios/Runner.xcworkspace"
INFO_PLIST="ios/Runner/Info.plist"

# # 🔢 自动递增 Build 号（已关闭）
# echo "🔢 Step 0: Bump build number"
# if /usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFO_PLIST" >/tmp/cfv.txt 2>/dev/null; then
#   CURRENT_BUILD=$(cat /tmp/cfv.txt)
#   if [[ "$CURRENT_BUILD" =~ ^[0-9]+$ ]]; then
#     NEXT_BUILD=$((CURRENT_BUILD + 1))
#   else
#     NEXT_BUILD=1
#   fi
# else
#   NEXT_BUILD=1
# fi
# /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $NEXT_BUILD" "$INFO_PLIST"
# echo "CFBundleVersion: $CURRENT_BUILD -> $NEXT_BUILD"

# 使用现有 CFBundleVersion 作为 IPA 命名，不做自增
CURRENT_BUILD=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFO_PLIST" 2>/dev/null || echo "0")
NEXT_BUILD="$CURRENT_BUILD"

# 获取时间戳用于命名 IPA，并带上 build 号（在确定 NEXT_BUILD 之后）
DATE_STR=$(date +"%y-%m-%d-%H-%M")
IPA_NAME="casdonn_${DATE_STR}_b${NEXT_BUILD}.ipa"

# # 🛰️ 推送 build 号到远端，确保打包前代码已同步（已关闭）
# echo "🌿 Step 0.5: Commit & push build number"
# if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
#   CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
#   git add "$INFO_PLIST"
#   git commit --only "$INFO_PLIST" -m "打包 build: $NEXT_BUILD"
#   git push origin
#   echo "✅ 已推送到远端分支 origin/$CURRENT_BRANCH"
# else
#   echo "⚠️ 未检测到 git 仓库，跳过 push 步骤"
# fi

# 1️⃣ 清理项目
echo "🧹 Step 1: Flutter clean + pub get"
flutter clean
flutter pub get

# 2️⃣ 安装依赖
echo "📦 Step 2: CocoaPods install"
cd ios
pod install --repo-update
cd ..

# 3️⃣ Flutter 构建
echo "🏗 Step 3: Flutter build ios --release"
flutter build ios --release --no-codesign

# 4️⃣ Xcode Archive
ARCHIVE_PATH="build/ios/archive/$APP_NAME.xcarchive"
echo "📦 Step 4: Xcode Archive"
xcodebuild -workspace "$PROJECT_PATH" \
           -scheme "$APP_NAME" \
           -configuration "$CONFIGURATION" \
           -archivePath "$ARCHIVE_PATH" \
           -destination "generic/platform=iOS" \
           -allowProvisioningUpdates \
           clean archive

# 5️⃣ 生成 ExportOptions.plist
mkdir -p "$OUTPUT_DIR"
EXPORT_OPTIONS_PLIST="$OUTPUT_DIR/ExportOptions.plist"
cat > "$EXPORT_OPTIONS_PLIST" <<EOL
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>method</key>
  <string>$EXPORT_METHOD</string>
  <key>signingStyle</key>
  <string>automatic</string>
  <key>destination</key>
  <string>export</string>
  <key>compileBitcode</key>
  <false/>
  <key>uploadBitcode</key>
  <false/>
  <key>stripSwiftSymbols</key>
  <true/>
  <key>uploadSymbols</key>
  <true/>
  <key>manageAppVersionAndBuildNumber</key>
  <false/>
</dict>
</plist>
EOL

# 6️⃣ 导出 IPA
echo "📤 Step 5: Export IPA"
xcodebuild -exportArchive \
           -archivePath "$ARCHIVE_PATH" \
           -exportOptionsPlist "$EXPORT_OPTIONS_PLIST" \
           -exportPath "$OUTPUT_DIR" \
           -allowProvisioningUpdates

# 7️⃣ 重命名 IPA
IPA_PATH=$(find "$OUTPUT_DIR" -type f -name "*.ipa" | head -n 1)

if [ -f "$IPA_PATH" ]; then
  mv "$IPA_PATH" "$OUTPUT_DIR/$IPA_NAME"
  echo "✅ 已重命名为：$IPA_NAME"
  open "$OUTPUT_DIR"
  echo "🎉 打包成功！文件路径：$OUTPUT_DIR/$IPA_NAME"
else
  echo "❌ 未找到 IPA 文件，请检查导出步骤。"
fi

# 保持终端窗口打开
echo ""
echo "🍎 打包任务已结束。按任意键关闭窗口。"
read -n 1
